//
//  InTheRecordingViewController.m
//  录音
//
//  Created by ywy on 2016/12/22.
//  Copyright © 2016年 Wely. All rights reserved.
//

#import "InTheRecordingViewController.h"
#import "CLTRoundView.h"
#import "PCSEQVisualizer.h"
#import <AVFoundation/AVFoundation.h>
#import "RETabBarViewController.h"
#import "ReRecordModel.h"//  录音的model
#import "RESingleton.h"  // 单例
#import "RECheckLogin.h" // 登陆的检测
#import <SVProgressHUD/SVProgressHUD.h>
// 我的李勇 这是正在录音VC


@interface InTheRecordingViewController ()<AVAudioRecorderDelegate,UIAlertViewDelegate>
{
     NSTimer* _timer;
      int _recordTime;
    // 第二个计时器 记录 每个文件的 录制时间
    NSTimer * _timeerTwo;
    int _recordTimeTwo;
  
}
@property (nonatomic,strong) CLTRoundView *roudView;
@property(nonatomic,strong)  PCSEQVisualizer* eq;
// 记录时间的 数组
@property(nonatomic,strong) NSMutableArray *  timeArrTwo;
@property (nonatomic) AVAudioRecorder *recorder;
//录制音频的相关配置(需要一点专业知识)
@property (nonatomic) NSDictionary *audioSetting;
//用于存储音频的临时路径
@property (nonatomic) NSURL *tmpURL;
/// 请求下来的数据的信息
@property(nonatomic,strong) NSDictionary * dateDict;
// 用户当天录制总时长
@property(nonatomic,strong) NSMutableArray * recTimeLengthArr;
// 用户当天录制文件总时长
@property(nonatomic,strong) NSMutableArray * fileTimeLengthArr;
// 文件的时长
@property(nonatomic,copy)NSString *  timeStr;
// 文件的个数
@property(nonatomic,strong) NSMutableArray * fileArr;
// 是否录音中
@property(nonatomic,assign) BOOL isRecoredIng;

@end
@implementation InTheRecordingViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    RETabBarViewController * tabBar = (RETabBarViewController *)self.tabBarController;
    //自定义隐藏Tabbar
    //    tabBar.bottomView.hidden = NO;
    //    tabBar.bottomView.alpha = 1;
    //    tabBar.bottomView.backgroundColor = [UIColor redColor];
    [tabBar HideTabarView:YES];
    [self.navigationController.navigationItem setHidesBackButton:YES];
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(backPop)];
     self.navigationItem.leftBarButtonItem = rightItem;
     UIImageView * firstImageView  =[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"录制中"]];
     firstImageView.frame = CGRectMake(0, 0, 37, 17);
     self.navigationItem.titleView=firstImageView;
    
}
-(void)backPop
{
    UIAlertView * alertView  =  [[UIAlertView alloc] initWithTitle:@"客官不要啊！" message:@"确定要返回吗? 录音音频不做保存,三思啊" delegate:self cancelButtonTitle:@"在考虑一下" otherButtonTitles:@"毫不犹豫", nil];
    [alertView show];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [self.navigationController popViewControllerAnimated:YES];
        [[NSFileManager defaultManager] removeItemAtURL:self.tmpURL error:nil];
        self.isRecoredIng = NO;
        [_timeerTwo invalidate];
        [_timer invalidate];
        _recorder = nil;
        [self.eq stop];
        
    }
}

- (NSURL *)tmpURL{
    if (!_tmpURL) {
        //~/tmp/0000
        NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:@"0000.caf"];
        //把path转成URL, 转化本地文件路径的.
        _tmpURL = [NSURL fileURLWithPath:path];
    }
    return _tmpURL;
}
- (NSDictionary *)audioSetting{
    if (!_audioSetting) {
        //音频的录制属性
        NSMutableDictionary *dicM = [NSMutableDictionary new];
        //设置录制的格式, PCM是最高品质的caf格式
        [dicM setObject:@(kAudioFormatLinearPCM) forKey:AVFormatIDKey];
        //采样频率, 8000是电话采样频率, 一般录音足够
        [dicM setObject:@(8000) forKey:AVSampleRateKey];
        //设置麦克风声道数量, iOS就一个麦克风
        [dicM setObject:@1 forKey:AVNumberOfChannelsKey];
        //每个采样点位数, 可选数值8,16,24,32
        [dicM setObject:@8 forKey:AVLinearPCMBitDepthKey];
        //是否采用浮点数采样
        [dicM setObject:@YES forKey:AVLinearPCMIsFloatKey];
        _audioSetting = dicM.copy;
    }
    return _audioSetting;
}
-(CLTRoundView *)roudView
{
    if (!_roudView) {
        _roudView = [[CLTRoundView alloc]initWithFrame:CGRectMake(0, 64+50, REScreenW, 300)];
    }
    return _roudView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.dateDict = [NSDictionary new];
    self.timeArrTwo = [NSMutableArray new];
    self.fileArr = [NSMutableArray new];
    self.isRecoredIng = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.roudView];
    [self requestBase];
//    [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
//        if (granted) {
//            // 用户同意获取数据
//            // 可以显示一个提示框告诉用户这个app没有得到允许？
//              [SVProgressHUD showErrorWithStatus:@"已经获取麦克风权限"];
//              [self requestBase];
//        } else {
//            [SVProgressHUD showErrorWithStatus:@"没有获取麦克风权限"];
//        }
//    }];
    // Do any additional setup after loading the view from its nib.
    
}

-(void)requestBase
{
    __weak typeof(self) weakSelf = self;
    NSMutableDictionary * dict = [NSMutableDictionary new];
    dict[@"cmd"] = @"getTimeLength";
    dict[@"uid"] = [UserDefaults objectForKey:@"userid"];
    [SVProgressHUD showWithStatus:@"获取每日任务中..."];
    [RECheckLogin POST:REBaseUrl parameters:dict progress:^(CGFloat prosser) {
    } success:^(id responseObject) {
        
        if ([responseObject[@"result"] isEqualToString:@"0"]) {
            [weakSelf baseStart:responseObject];
        }else
        {
//            [SVProgressHUD showErrorWithStatus:responseObject[@"resultNote"]];
        }
        [SVProgressHUD dismiss];
    } failure:^(NSError *error) {
              [SVProgressHUD showErrorWithStatus:@"查看网络!!"];
    }];
}
-(void)baseStart:(NSDictionary*)dict
{
    
     self.dateDict  = dict;
    [self recorderCLick];
    [self creatMideleView];
    [self creatEndView];
    [UIApplication sharedApplication].idleTimerDisabled = YES;
}

-(void)recorderCLick
{
    [self creeatRe];
    [self recordTimeStart];
}
- (void)recordTimeStart {
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(recordTimeTick) userInfo:nil repeats:YES];
    _timeerTwo = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(recordTimeTickTwo) userInfo:nil repeats:YES];
}
-(void)recordTimeTickTwo
{
    _recordTimeTwo +=1;
}
-(void)creeatRe
{
        //设置本项目对于音频处理是: 能录又能播
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    //让设置生效
    [[AVAudioSession sharedInstance] setActive:YES error:nil];
    NSError *error = nil;
    _recorder  =  [[AVAudioRecorder alloc] initWithURL:self.tmpURL settings:self.audioSetting error:
                   &error];
    _recorder.delegate = self;
    [_recorder record];
    //允许读取声音的大小
    _recorder.meteringEnabled = YES;
}

- (void)recordTimeTick {
    
    _recordTime +=1;
    [self updateAudioRecordTime];
    [_recorder updateMeters];//刷新音量数据
    float power = [_recorder averagePowerForChannel:0];
    power = power + 160  - 50;
    int dB = 0;
    if (power < 0.f) {
        dB = 0;
    } else if (power < 40.f) {
        dB = (int)(power * 0.875);
    } else if (power < 100.f) {
        dB = (int)(power - 15);
    } else if (power < 110.f) {
        dB = (int)(power * 2.5 - 165);
    } else {
        dB = 110;
    }
    
    NSLog(@"不停的 打印 数据的信息 %d",dB);
    
    if (dB <= 50) {
        [self.timeArrTwo addObject:@"57"];
    }else{
        [self.timeArrTwo removeLastObject];
    }
    if (self.timeArrTwo.count == 3) {
        // 中断录音  3s 声音低于57DB
        self.isRecoredIng = YES;
        [_recorder stop];
    }
}

-(void)updateAudioRecordTime
{
    int  minnute;
    int second;
    NSArray * timeArr;
    
    
    NSString * str = @"00:00";
    if (self.dateDict[@"timeLength"] == nil || [self.dateDict[@"timeLength"] isEqualToString:@"0"]) {
            timeArr = [str componentsSeparatedByString:@":"];
    }else
    {
           timeArr  = [self.dateDict[@"timeLength"] componentsSeparatedByString:@":"];
    }
    
        minnute = (_recordTime+ ([timeArr[0] intValue] * 60 + [timeArr[1] intValue]))/60;
        second = (_recordTime+ ([timeArr[0] intValue] * 60 + [timeArr[1] intValue]))-(minnute*60);
  // 当天录制的
    _roudView.progressView.font = [UIFont fontWithName:@"MyriadPro-BoldCond" size:50];
    _roudView.progressView.textAlignment = NSTextAlignmentCenter;
    _roudView.progressView.textColor = RERGBColor(74, 74, 74);
    NSMutableAttributedString *titleStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%02d:%02d",minnute,second]];
    [titleStr addAttribute:NSForegroundColorAttributeName value:RERGBColor(171, 171, 171) range:NSMakeRange(2,1)];
    _roudView.progressView.attributedText = titleStr;
    // 传入百分比的时候，传入 小数，  0.1 - 1 范围内  <==>  1 - 100
    self.roudView.percent = (CGFloat) ( _recordTime+([timeArr[0] intValue] * 60 + [timeArr[1] intValue]))/([self.dateDict[@"dayCount"]intValue]*60);
}

-(void)creatMideleView
{
    UIButton * middleButton = [UIButton buttonWithType:0];
    middleButton.frame = CGRectMake(REScreenW/2-41, 375+50, 82, 69);
    [middleButton setBackgroundImage:[UIImage imageNamed:@"end"] forState:0];
    [middleButton addTarget:self action:@selector(endClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:middleButton];
}
// 结束按钮
-(void)endClick
{
    self.isRecoredIng = NO;
    [_timeerTwo invalidate];
    [_timer invalidate];
    [_recorder stop];
    [self.eq stop];
    // 结束录音之后，取消屏幕长亮
    [UIApplication sharedApplication].idleTimerDisabled = NO;
}

-(void)postEndRecording
{
    __weak typeof(self) weakSelf = self;
    NSMutableArray * timeArr = [NSMutableArray new];
    
    for (NSInteger i = 0; i<self.fileArr.count; i++) {
        NSArray * stArr =[self.fileArr[i] componentsSeparatedByString:@":"];
        [timeArr addObject:[NSString stringWithFormat:@"%d",[stArr[0] intValue]*60+[stArr[1] intValue]]];
    }
    
    
    NSNumber *sum = [timeArr valueForKeyPath:@"@sum.floatValue"];
    [timeArr removeAllObjects];
    // 文件录制时间之和
    int  minnute = [sum intValue]/60;
    int second = [sum intValue]-minnute*60;
    // 网络的FileTimeLength
    
    
    
   NSArray *  timeArrFirst  = [self.dateDict[@"fileTimeLength"] componentsSeparatedByString:@":"];
    
   int  totalSecondFile= ([timeArrFirst[0] intValue] * 60 + [timeArrFirst[1] intValue])+[sum intValue];
    int minnutefile = totalSecondFile/60;
    int secondfile =totalSecondFile-(minnutefile*60);
    
       //  网络的  timeLength
    NSArray *  timeArrTime  = [self.dateDict[@"timeLength"] componentsSeparatedByString:@":"];
    int  totalSecondTime = ([timeArrTime[0] intValue] * 60 + [timeArrTime[1] intValue])+_recordTime;
//  录制的 时间
    int  minnuteRe  = totalSecondTime/60;
    int  secondRE  = totalSecondTime-(minnuteRe*60);
    
    
    NSMutableDictionary * dict = [NSMutableDictionary new];
    dict[@"cmd"] = @"endRecording";
    dict[@"uid"] = [UserDefaults objectForKey:@"userid"];
    dict[@"recTimeLength"] =  [NSString stringWithFormat:@"%02d:%02d",minnuteRe,secondRE];
    
    dict[@"fileTimeLength"] = [NSString stringWithFormat:@"%02d:%02d", minnutefile,secondfile];
    
    [SVProgressHUD showWithStatus:@"提交中...."];
    [RECheckLogin POST:REBaseUrl parameters:dict progress:^(CGFloat prosser) {
    } success:^(id responseObject) {
        if ([responseObject[@"result"] isEqualToString:@"0"]) {
            [SVProgressHUD showSuccessWithStatus:[NSString stringWithFormat:@"录制%lu文件,录制时间%02d:%02d",(unsigned long)weakSelf.fileArr.count,minnute,second]];
                [weakSelf.timeArrTwo removeAllObjects];
            
                [[NSNotificationCenter defaultCenter] postNotificationName:@"pop" object:nil];
                [self.navigationController popToRootViewControllerAnimated:YES];
        }else
        {
//            [SVProgressHUD showErrorWithStatus:responseObject[@"resultNote"]];
        }
           [SVProgressHUD dismiss];
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"查看网络！！！"];
    }];
}

-(NSString*)saveRecordingWithName:(NSString *)RE
{
    NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    NSString *path = [docPath stringByAppendingPathComponent:RE];
    path = [path stringByAppendingPathExtension:@"caf"];
    // 移动 tmp 到 Documents 中
    NSURL *toURL = [NSURL fileURLWithPath:path];
    [[NSFileManager defaultManager] moveItemAtURL:self.tmpURL toURL:toURL error:nil];
    return path;
}

-(void)creatEndView
{
    self.eq = [[PCSEQVisualizer alloc]initWithNumberOfBars:REScreenW/10.7];
    self.eq.frame = CGRectMake(0, REScreenH-82, REScreenW, 80);
    [self.view addSubview:self.eq];
    [self.eq start];
}
//代理: 当录音结束时触发
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag{
  
  
    ReRecordModel *audioDataModel = [[ReRecordModel alloc] init];
    audioDataModel.titleStr= @"RE";
    audioDataModel.baseUrl  = [self saveRecordingWithName:[RECheckLogin stringFromDateTwo:[NSDate date]]];
    
    int  minnute = _recordTimeTwo/60;
    int second = _recordTimeTwo-minnute*60;
    
    
    audioDataModel.currentTime = [NSString stringWithFormat:@"%02d:%02d",minnute,second];
    audioDataModel.date   = [RECheckLogin stringFromDate:[NSDate date]];
    audioDataModel.isUpPost = @"noUp";
    audioDataModel.isClas = @"noClass";
    audioDataModel.albumName = @"Wely";
    audioDataModel.firstStr = @"1";
    audioDataModel.secondStr = @"2";
    audioDataModel.thirdStr = @"3";
    audioDataModel.idStr = @"00000";
    if (_recordTimeTwo > 5) {
        // 时长<5s
            [[RESingleton defaultCent] insertModel:audioDataModel];
            [self.fileArr addObject:audioDataModel.currentTime];
    };
    _recordTimeTwo = 0;
    [self.timeArrTwo removeAllObjects];
    if (self.isRecoredIng == YES ) {
        [self creeatRe];
    }else if(self.isRecoredIng == NO)
    {
         [self postEndRecording];
    }
    
}


-(void)dealloc
{
    
    _recorder.delegate = nil;
    _recorder = nil;
    [_timer invalidate];
    [_timeerTwo invalidate];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
